<template>
  <basic-dialog :visible="show"
                minWidth="1000px"
                :isShowInnerLoading = 'isShowInnerLoading'
                title="质检录入">
    <div class="flex items-center justify-between padding-20" style="padding-bottom: 10px">
      <div class="flex-1">加工班次：{{subData.shiftName}}</div>
      <div class="flex-1">报检数量：{{subData.qualityControlCount}}</div>
      <div class="flex-1">质检数量：{{subData.qualityCount}}</div>
      <div class="flex-1">不良数量：{{subData.defectiveCount}}</div>
<!--      <div class="flex-1">让步数量：{{subData.compromiseCount}}</div>-->
    </div>

    <q-form greedy ref="form" >
      <div style="padding: 0 20px">
        <div class="form-item inline-block" style="width: 266px">
          <span class="form-name form-name font-14" style="padding-right: 6px;width: 77px">填报日期：</span>
          <date-picker
            v-model="inputTime"
            type="date"
            :range="false"
            :clearable="false"
            :editable="false"
            style="width: 182px"
            :disabled-date="disabledAfterToday"
            :rules="val => (val && val.length > 0) || '不能为空'"
            format="YYYY-MM-DD"
            placeholder="请选择填报日期"/>
        </div>
        <div class="form-item inline-block padding-l-20 flex" >
          <div class="row">
            <div class="q-mt-sm"><span class="font-size-14">质检类型:</span></div>
            <q-radio
              v-model="spotCheck"
              :val="0"
              label="全检"
            />
            <q-radio
              v-model="spotCheck"
              :val="1"
              label="抽检"
            />
          </div>
        </div>

        <q-input
          v-if="spotCheck"
          v-model.number="qualityCount"
          ref="qualityCount"
          outlined
          dense
          maxlength="6"
          mask="######"
          class="inline-block margin-l-20"
          style="max-width: 140px"
          placeholder="请输入质检数量"
          :rules="[val =>  /^[1-9]\d*$/.test(val) && val > 0 || '请输入正整数',
            val => val <= waitInput || '数量超出']"
        />

        <!--        产品执意要加的仪式感操作步骤-->
        <div class="form-item inline-block padding-l-20 flex" >
          <div class="row">
            <div class="q-mt-sm"><span class="font-size-14">质检结果:</span></div>
            <q-radio
              v-model="result"
              :val="1"
              label="有不良品"
            />
            <q-radio
              v-model="result"
              :val="0"
              label="全部合格"
            />
          </div>
        </div>
      </div>
      <q-toolbar class="tab padding-l-20 padding-r-20" style="min-height: 36px" v-show="result">
        <q-tabs
          v-model="tab"
          shrink
          stretch
          dense
          inline-label
          align="left"
          active-color="primary"
          indicator-color="primary"
        >
          <q-tab name="bad" label="不良录入" class="item-tab-label" />
  <!--        <q-tab name="compromise" label="让步录入" class="item-tab-label" />-->
        </q-tabs>
      </q-toolbar>
    </q-form>
    <q-separator class="line"  v-show="result"/>
    <q-form greedy @submit="validateData" ref="submitQuality">
      <!-- 不良品录入 -->
      <q-card style="margin: 20px; box-shadow: none" v-show="tab === 'bad' && result">
        <q-card-section class="dialog-title" style="background-color: #F3F3F3">
          <div class="text-center dialog-title" style="padding-left: 0; text-align: left" >
            <span class="font-size-16">不良录入表</span>
            <q-btn
              style="font-size: 18px; color: white"
              flat
              round
              dense
              class="iconfont icontubiao-39 text-primary close-btn dialog"
              @click="addDefectiveCauses"
            />
          </div>
        </q-card-section>
        <q-card-section class="bordered scroll-box" style="padding: 0; max-height: 370px" >
          <div v-for="(item, index) in defectiveData" :key="index" class="padding-t-20">
            <div class="flex">
              <div style="width: 50px; padding-left: 20px; line-height: 144px">{{index + 1}}</div>
              <div style="flex: 1">
                <div class="row">
                  <q-select
                    class="select col margin-r-20"
                    outlined
                    dense
                    emit-value
                    map-options
                    options-dense
                    :options="partscauseList"
                    v-model="item.gid"
                    style="max-width: 270px"
                    @input="getPartscauseItem(item.gid, item, index)"
                    :rules="[val => val !== null || '请选择原因类型']"
                  >
                    <template v-slot:no-option>
                      <div class="no-option" />
                    </template>
                    <template v-slot:before>
                      <span class="font-size-16 text-black fuck-width"
                      >不良类型:</span
                      >
                    </template>
                  </q-select>

                  <q-select
                    class="select col margin-r-20"
                    outlined
                    dense
                    emit-value
                    map-options
                    options-dense
                    :options="item.partscauseItemList"
                    v-model="item.defective"
                    style="max-width: 270px"
                    @input="onInput"
                    :rules="[
                   val => repeat('defective', item.defective, index) || '同班次下已选相同不良原因',
                   val => val !== null || '请选择不良原因'
                 ]"
                  >
                    <template v-slot:no-option>
                      <div class="no-option" />
                    </template>
                    <template v-slot:before>
                      <span class="font-size-16 text-black fuck-width"
                      >不良原因:</span
                      >
                    </template>
                  </q-select>

                  <q-input
                    v-model.number="item.count"
                    outlined
                    dense
                    maxlength="6"
                    mask="######"
                    style="max-width: 240px"
                    placeholder="请输入数量"
                    :rules="[val =>  /^[1-9]\d*$/.test(val) && val > 0 || '请输入正整数']"
                  >
                    <template v-slot:before>
                      <span
                        class="font-size-16 text-black fuck-width"
                        style="text-align: right"
                      >不良数量:</span
                      >
                    </template>
                  </q-input>
                </div>
                <div style="margin-top: 2px">
                  <q-input
                    v-model.trim="item.remark"
                    type="textarea"
                    counter
                    autogrow
                    maxlength="50"
                    outlined
                    placeholder="请输入不良说明内容"
                    class="textarea"
                  >
                    <template v-slot:before>
                      <span class="font-size-16 text-black">不良说明:</span>
                    </template>
                    <template v-slot:append>
                      <q-icon
                        name="iconfont icontubiao2-93"
                        color="primary"
                        class="cursor-pointer font-18"
                        @click="onShowSymbol(item, index)"
                      />
                    </template>
                  </q-input>
                </div>
                <div style="margin-top: 2px">
                  <q-input
                    v-model.trim="item.strategy"
                    type="textarea"
                    counter
                    autogrow
                    maxlength="50"
                    outlined
                    placeholder="请输入改善对策内容"
                    class="textarea"
                  >
                    <template v-slot:before>
                      <span class="font-size-16 text-black">改善对策:</span>
                    </template>
                  </q-input>
                </div>
              </div>
              <div
                class="text-center"
                style="width: 60px; line-height: 134px"
              >
                <table-btn btn-type="delete" @click="delQualityItem('defective', index)"/>
              </div>
            </div>
          </div>
        </q-card-section>
      </q-card>
      <!-- 不良品录入End -->
      <!-- 底部按钮 -->
      <q-separator />
      <div class="dialog-footer text-center margin-t-10 form-inline justify-center" style="padding-bottom: 10px">
        <q-btn
          outline
          label="取消"
          color="primary"
          @click="show = false; result = null"
          class="q-mr-md"
        />
        <q-btn
          unelevated
          label="确认"
          color="primary"
          type="submit"
          :disable="!!(result && compromiseData.length + defectiveData.length <= 0)"
        />
      </div>
    </q-form>
    <add-symbol-dialog :show="isShowSymbol" @close="isShowSymbol = false" @onSetItem="onSetItem" />
  </basic-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { getCauseItem, getCauseTypeList } from 'src/boot/system/reason'
import addSymbolDialog from './add-symbol-dialog'
import { addQualitySubCauses } from 'src/boot/job/quality-order'
import _ from 'lodash'
import moment from 'moment'
const disabledAfterToday = (date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date > today
}
export default {
  NAME: 'add-quality-item',
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  components: {
    addSymbolDialog
  },
  data () {
    return {
      qualityCount: null, // 质检数量
      result: null, // 质检结果。产品执意要的仪式感，防手滑。说了两次说不通,因此加个虚假的柱子
      spotCheck: 0, // 抽检
      inputTime: new Date(new Date()),
      disabledAfterToday: disabledAfterToday,
      show: false,
      symbolData: null,
      isShowSymbol: false, // 符号弹窗
      isShowInnerLoading: false, // 加载
      details: {}, // 详情信息
      // 表格不分页
      pagination: {
        rowsPerPage: 0
      },
      // 不良录入列表
      defectiveData: [],
      // 让步录入列表
      compromiseData: [],
      waitInput: 0, // 待录入数
      concessionList: [], // 让步原因下拉数据
      partscauseList: [], // 不良原因类型下拉数据
      partscauseItemList: [], // 不良原因下拉数据
      subData: {}, // 子质检单数据
      tab: 'bad'
    }
  },
  watch: {
    // 全屏的时候防止错乱, 定位归零
    result (val) {
      this.defectiveData = []
      val && (this.addDefectiveCauses())
    }
  },
  methods: {
    showDialog (data, subData) {
      this.show = true
      this.isShowInnerLoading = true
      this.inputTime = new Date(new Date())
      this.spotCheck = 0
      this.qualityCount = null
      this.defectiveData = []
      this.compromiseData = []
      this.details = data
      this.subData = subData
      // this.waitInput = subData.qualityControlCount - subData.defectiveCount - subData.compromiseCount
      // 不可超过待检数量-质检数量
      this.waitInput = subData.qualityControlCount - subData.qualityCount
      // this.getCauseList()
      this.getPartscauseList()
    },
    validateData () {
      if (this.result) {
        this.spotCheck ? this.$refs.form.validate(true).then(result => {
          if (result) {
            this.isOver()
          }
        }) : this.isOver()
      } else {
        this.submitQuality()
      }
    },
    // 是否超出
    isOver () {
      this.isShowInnerLoading = true
      const defectiveCount = _.sumBy(this.defectiveData, function (o) {
        return Number(o.count)
      })
      const compromiseCount = _.sumBy(this.compromiseData, function (o) {
        return Number(o.count)
      })
      const max = this.spotCheck ? this.qualityCount : this.waitInput
      if ((defectiveCount + compromiseCount) > max) {
        const tips = this.spotCheck ? '所填写的不良数量已超出抽检数量。' : '所填写的不良数量已超出待录入数量（报检数量-质检数量）'
        this.$message.error(tips)
        this.isShowInnerLoading = false
        return false
      } else {
        this.submitQuality()
      }
    },
    // 获取录入列表
    getVos () {
      let params = []
      // 不良录入
      if (this.defectiveData.length > 0) {
        this.defectiveData.forEach(item => {
          let itemParams = {
            count: Number(item.count),
            causeId: item.defective,
            gid: item.gid,
            // 13期
            remark: item.remark,
            inputType: '1',
            causeName: item.partscauseItemList.find(v => v.value === item.defective).label,
            workshopId: this.details.workshopId,
            improveStrategy: item.strategy
          }
          params.push(itemParams)
        })
      }
      // 让步录入
      if (this.compromiseData.length > 0) {
        this.compromiseData.forEach(item => {
          let itemParams = {
            count: Number(item.count),
            causeId: item.concession,
            causeName: this.concessionList.find(v => v.value === item.concession).label,
            workshopId: this.details.workshopId,
            inputType: '2',
            // 13期
            remark: item.remark
          }
          params.push(itemParams)
        })
      }
      return params
    },
    // 提交
    submitQuality () {
      const data = {
        inputTime: moment(this.inputTime).format('YYYY-MM-DD')
      }
      this.result && (data['vos'] = this.getVos())
      this.spotCheck && (data['qualityCount'] = this.qualityCount)
      this.batchCreateQuality(data)
    },
    // 批量新增
    batchCreateQuality (params) {
      addQualitySubCauses(params, this.details.id, this.subData.id).then(res => {
        if (res.code === '1200') {
          this.$message.success('添加成功')
          this.show = false
          this.$emit('getList')
        }
      }).finally(() => {
        this.isShowInnerLoading = false
      })
    },
    // 新增不良原因行
    addDefectiveCauses () {
      this.isShowInnerLoading = true
      let item = {
        remark: '',
        gid: this.partscauseList[0] ? this.partscauseList[0].value : null,
        count: 1,
        defective: null
      }
      if (this.partscauseList.length) {
        item.partscauseItemList = this.getPartscauseItem(this.partscauseList[0].value, item)
      } else {
        item.partscauseItemList = []
        item.defective = null
        this.defectiveData.push(item)
        this.isShowInnerLoading = false
        const dom = this.$refs.submitQuality
        setTimeout(() => {
          dom.validate()
        }, 0)
      }
    },
    // 新增让步原因行
    addCompromiseCauses () {
      const item = {
        concession: null,
        remark: '',
        count: 1
      }
      if (this.concessionList.length > 0) {
        item.concession = this.concessionList[0].value
      }
      this.compromiseData.push(item)
      const dom = this.$refs.submitQuality
      setTimeout(() => {
        dom.validate()
      }, 0)
    },
    repeat (type, cause, indexId) {
      let flag = true
      if (type === 'compromise') {
        if (this.compromiseData.length > 1) {
          const isDiffList = this.compromiseData.filter((item, index) => indexId !== index && item.concession === cause)
          flag = !isDiffList.length
        }
      } else if (type === 'defective') {
        if (this.defectiveData.length > 1) {
          const isDiffList = this.defectiveData.filter((item, index) => indexId !== index && item.defective === cause)
          flag = !isDiffList.length
        }
      }
      return flag
    },
    // 校验
    repeatCount () {
      let flag = true
      let count = 0
      if (this.compromiseData.length > 0) {
        this.compromiseData.forEach(i => {
          count += Number(i.count)
          if (count > this.waitInput) {
            flag = false
            return false
          }
        })
      }
      if (this.defectiveData.length > 0) {
        this.defectiveData.forEach(i => {
          count += Number(i.count)
          if (count > this.waitInput) {
            flag = false
            return false
          }
        })
      }
      return flag
    },
    // 删除行
    delQualityItem (type, indexId) {
      if (type === 'compromise') {
        this.compromiseData.splice(indexId, 1)
        this.compromiseData.forEach((i, index) => {
          indexId = index
        })
      } else if (type === 'defective') {
        this.defectiveData.splice(indexId, 1)
        this.defectiveData.forEach((i, index) => {
          indexId = index
        })
      }
    },
    // 触发校验
    onInput () {
      this.$refs.submitQuality.validate()
    },
    // 根据零件不良原因类型代码查询零件不良原因
    getPartscauseItem (typeId, item, index) {
      this.isShowInnerLoading = true
      const params = {
        id: typeId,
        showDisable: false
      }
      // item.defective = null
      getCauseItem(params).then(res => {
        let partscauseList = []
        if (res.data.length) {
          res.data.forEach(o => {
            partscauseList.push({
              value: o.id,
              label: o.label
            })
          })
          item.defective = res.data[0].id
        } else {
          item.defective = null
        }
        if (index === undefined) {
          item.partscauseItemList = []
          item.partscauseItemList = partscauseList
          this.defectiveData.push(item)
        } else {
          this.defectiveData[index].partscauseItemList = partscauseList
        }

        const dom = this.$refs.submitQuality
        setTimeout(() => {
          dom.validate()
        }, 0)
      }).finally(() => {
        this.isShowInnerLoading = false
      })
    },
    // 获取原因类型
    getCauseList () {
      getCauseTypeList(2).then(res => {
        if (res.data.length > 0) {
          this.getConcessioncauseList(res.data[0].id)
        }
      })
    },
    // 获取让步原因列表
    getConcessioncauseList (typeId) {
      const params = {
        showDisable: false,
        causeGroupId: typeId
      }
      getCauseItem(params).then(res => {
        this.concessionList = []
        if (res.data.length > 0) {
          res.data.forEach(o => {
            this.concessionList.push({
              value: o.id,
              label: o.label
            })
          })
        }
      }).finally(() => {
        this.isShowInnerLoading = false
      })
    },
    // 获取不良原因类型列表
    getPartscauseList () {
      getCauseTypeList(1).then(res => {
        this.partscauseList = []
        if (res.data.length > 0) {
          res.data.forEach(o => {
            this.partscauseList.push({
              value: o.id,
              label: o.label
            })
          })
        }
      }).finally(() => {
        this.result = 1
        this.isShowInnerLoading = false
      })
    },
    // 选择符号
    onShowSymbol (item, index) {
      this.symbolData = item
      this.isShowSymbol = true
    },
    onSetItem (val) {
      if (this.symbolData.remark.length < 50) {
        this.symbolData.remark = `${this.symbolData.remark}${val}`
      }
    }
  }
}
</script>

<style scoped lang="stylus">
  .bordered,.bordered:last-child {
    border 1px solid #D3D3D3
    border-top 0
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
    &>div{
      border-bottom 1px solid #D3D3D3
      &:nth-child(even){
        background-color #f9f9f9
      }
      &:last-child{
        border-bottom 0
      }
    }
  }
  .p-t-10{
    padding-top 10px
  }
  .fuck-width{
    width 68px
  }
  .item-tab-label{
    margin 0
    padding 0 20px
    min-height 36px
    >>>.q-tab__content{
      height 36px
    }
    >>>.q-tab__label{
      line-height 1
    }
  }
  >>>.textarea{
    .q-field__control{
      align-items flex-end
    }
  }
</style>
